package bb.lanxing.activity.login

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.CountDownTimer
import android.text.Editable
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextWatcher
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.view.View
import android.widget.CheckBox
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import bb.lanxing.App
import bb.lanxing.R
import bb.lanxing.activity.agreement.AgreementActivity
import bb.lanxing.activity.base.BaseActivity
import bb.lanxing.activity.interfaces.IGetAuthCodeView
import bb.lanxing.activity.mine.ProfileEditActivity
import bb.lanxing.activity.mine.ProfileEditActivity.TYPE_SIMPLE
import bb.lanxing.common.config.Constants
import bb.lanxing.common.config.Constants.INTERVAL_1_MIN
import bb.lanxing.common.config.Constants.INTERVAL_1_SEC
import bb.lanxing.common.config.UmengEventConst
import bb.lanxing.manager.SharedManager
import bb.lanxing.model.database.User
import bb.lanxing.model.event.MyProfileEvent
import bb.lanxing.mvp.presetner.GetAuthCodePresenterImpl
import bb.lanxing.mvp.presetner.i.IGetAuthCodePresenter
import bb.lanxing.network.BiCiCallback
import bb.lanxing.network.MyHttpClient
import bb.lanxing.util.BusProvider
import bb.lanxing.util.JsonUtil
import bb.lanxing.util.Validator
import bb.lanxing.utils.IntentUtils
import com.umeng.analytics.MobclickAgent
import org.json.JSONException
import org.json.JSONObject
import org.litepal.LitePal.where

class PhoneRegisterActivity : AgreementActivity(), IGetAuthCodeView {
    private lateinit var checkBoxUserAgreement: CheckBox
    private lateinit var emailRegisterBtn: TextView
    private lateinit var getAuthcodeBtn: TextView
    private lateinit var inputPhoneNumber: String
    private lateinit var mEmailRegisterBtn: View
    private lateinit var mGetAuthcodeBtn: View
    private lateinit var mRegisterBtn: View
    private lateinit var mVoiceView: View
    private lateinit var edt_phone: EditText
    private lateinit var edt_pwd: EditText
    private lateinit var edt_pwd_again: EditText
    private lateinit var edt_authcode: EditText

    private lateinit var img_del_phone: ImageView
    private lateinit var img_del_pwd: ImageView
    private lateinit var img_del_pwd_again: ImageView
    private lateinit var img_del_authcode: ImageView

    private lateinit var presenter: IGetAuthCodePresenter
    private lateinit var registerBtn: TextView
    private lateinit var tvUserAgreement: TextView
    private lateinit var voiceView: TextView

    private var mTimer: CountDownTimer? = null
    private var isCountingDown = false
    private var captcha = ""
    override fun onCreate(bundle: Bundle?) {
        super.onCreate(bundle)
        setContentView(R.layout.activity_register)
        bindView(window.decorView)
        setupActionBar(true)
        presenter = GetAuthCodePresenterImpl(this)
        emailRegisterBtn.setText(R.string.mine_register_title_email_register)
        registerBtn.isEnabled = false
        getAuthcodeBtn.isEnabled = false
        checkBoxUserAgreement.setOnCheckedChangeListener { _, _ -> setRegisterBtnStatus() }
        tvUserAgreement.text = getSpannableStringBuilder(this@PhoneRegisterActivity)
        tvUserAgreement.movementMethod = LinkMovementMethod.getInstance()
        val textWatcher = object : TextWatcher {
            override fun afterTextChanged(editable: Editable) {}
            override fun beforeTextChanged(charSequence: CharSequence, i: Int, i2: Int, i3: Int) {}
            override fun onTextChanged(charSequence: CharSequence, i: Int, i2: Int, i3: Int) {
                setRegisterBtnStatus()
            }
        }
        edt_phone.setOnFocusChangeListener { _, hasFocus ->
            run {
                if (edt_phone.getText().isEmpty() || !hasFocus) {
                    img_del_phone.setVisibility(View.GONE)
                } else {
                    img_del_phone.setVisibility(View.VISIBLE)
                }
            }
        }
        edt_phone.addTextChangedListener(textWatcher)
        edt_phone.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (edt_phone.text.isNotEmpty()) {
                    img_del_phone.visibility = View.VISIBLE
                } else {
                    img_del_phone.visibility = View.GONE
                }
            }

            override fun afterTextChanged(s: Editable?) {
            }
        })

        edt_pwd.addTextChangedListener(textWatcher)
        edt_pwd.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (edt_pwd.text.isNotEmpty()) {
                    img_del_pwd.visibility = View.VISIBLE
                } else {
                    img_del_pwd.visibility = View.GONE
                }
            }

            override fun afterTextChanged(s: Editable?) {
            }
        })

        edt_pwd.setOnFocusChangeListener { _, hasFocus ->
            run {
                if (edt_pwd.getText().isEmpty() || !hasFocus) {
                    img_del_pwd.setVisibility(View.GONE)
                } else {
                    img_del_pwd.setVisibility(View.VISIBLE)
                }
            }
        }
        edt_pwd_again.addTextChangedListener(textWatcher)
        edt_pwd_again.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (edt_pwd_again.text.isNotEmpty()) {
                    img_del_pwd_again.visibility = View.VISIBLE
                } else {
                    img_del_pwd_again.visibility = View.GONE
                }
            }

            override fun afterTextChanged(s: Editable?) {
            }
        })

        edt_pwd_again.setOnFocusChangeListener { _, hasFocus ->
            run {
                if (edt_pwd_again.getText().isEmpty() || !hasFocus) {
                    img_del_pwd_again.setVisibility(View.GONE)
                } else {
                    img_del_pwd_again.setVisibility(View.VISIBLE)
                }
            }
        }
        edt_authcode.addTextChangedListener(textWatcher)
        edt_authcode.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (edt_authcode.text.isNotEmpty()) {
                    img_del_authcode.visibility = View.VISIBLE
                } else {
                    img_del_authcode.visibility = View.GONE
                }
            }

            override fun afterTextChanged(s: Editable?) {
            }
        })

        edt_authcode.setOnFocusChangeListener { _, hasFocus ->
            run {
                if (edt_authcode.getText().isEmpty() || !hasFocus) {
                    img_del_authcode.setVisibility(View.GONE)
                } else {
                    img_del_authcode.setVisibility(View.VISIBLE)
                }
            }
        }

    }

    fun setRegisterBtnStatus() {
        val length = edt_phone.length()
        val ret =
            length > 0 && edt_pwd.length() > 0 && edt_pwd_again.length() > 0 && checkBoxUserAgreement.isChecked
        getAuthcodeBtn.isEnabled = ret
        registerBtn.isEnabled = ret && edt_authcode.length() > 0
    }

    fun onRegisterBtnClick(view: View) {
        register()
    }

    private fun register() {
        MobclickAgent.onEventValue(this, UmengEventConst.ACCOUNT_REGISTER_PHONE_IN, null, 1)
        val phone = edt_phone.text.toString()
        val pwd = edt_pwd.text.toString()
        val pwdAgain = edt_pwd_again.text.toString()
        val authCode = edt_authcode.text.toString()
        if (!Validator.isPhoneNumber(phone)) {
            App.getContext().showMessage(R.string.mine_profile_phone_not_valid)
            edt_phone.requestFocus()
        } else if (pwd.length < 6 || pwdAgain.length < 6) {
            App.getContext().showMessage(R.string.mine_profile_password_too_short)
            edt_pwd.requestFocus()
        } else if (pwd.length > 20 || pwdAgain.length > 20) {
            App.getContext().showMessage(R.string.mine_profile_password_too_long)
            edt_pwd_again.requestFocus()
        } else if (!pwd.equals(pwdAgain)) {
            toast(R.string.mine_profile_password_not_same)
        } else {
            try {
                val parseInt: Int = authCode.toInt()
                showMyProgressDialog(R.string.mine_register_dialog_registering)
                MyHttpClient.register(object : BiCiCallback(this, true) {
                    @Throws(JSONException::class)
                    override fun onResponseString(result: String) {
                        val jSONObject = JSONObject(result)
                        val code = jSONObject.getInt("code")
                        if (200 != code) {
                            val msg = jSONObject.getString("msg")
                            App.getContext().showMessage(msg)
                            return
                        }
                        val token = JsonUtil.getStringValue(SharedManager.KEY_TOKEN, jSONObject)
                        SharedManager.getInstance().setValue(SharedManager.KEY_TOKEN, token)
                        val jsonData = jSONObject.getJSONObject("data")
                        val i = jsonData.getInt("userid")

                        val user = User()
                        val string = jsonData.getString("username")
                        val string2 = jsonData.getString("enuid")

                        val userTemp = where("uid=?", i.toString()).findFirst(
                            User::class.java
                        )

                        if (null == userTemp) {

                            user.uid = i

                            user.name = string
                            user.enuid = string2
                            user.phone = phone
                            user.height = Constants.HEIGHT_DEFAULT

                            user.save();
                            App.getContext().setSigninUser(user)
                        } else {
                            userTemp.name = string
                            userTemp.enuid = string2
                            userTemp.setPhone(phone)
                            userTemp.save()
                            App.getContext().setSigninUser(userTemp)
                        }

                        SharedManager.getInstance().userPhone = phone
                        SharedManager.getInstance().userId = i
                        loginSuccess()
                    }
                }, 0, phone, parseInt, pwd)
            } catch (unused: NumberFormatException) {
                App.getContext().showMessage(R.string.mine_profile_authcode_not_valid)
                edt_authcode.requestFocus()
            }
        }
    }

    private fun loginSuccess() {
        MobclickAgent.onEventValue(this, UmengEventConst.ACCOUNT_REGISTER_PHONE_SUC, null, 1)
        SharedManager.getInstance().isSignoutFlag = true
        BusProvider.getInstance().post(MyProfileEvent(4))
        App.getContext().showMessage(R.string.mine_register_toast_successful)
        BusProvider.getInstance().post(MyProfileEvent(1))
        App.getContext().uploadDeviceToken()
        startActivity(Intent(this, ProfileEditActivity::class.java).putExtra("type", TYPE_SIMPLE));
        finish()
    }

    fun getAuthCodeBtnClick(view: View) {
        val text = edt_phone.text.toString()
        if (Validator.isPhoneNumber(text)) {
            getAuthcodeBtn.isEnabled = false
            startCountDown()
            presenter.getAuthCode(text, 0, 0)
            return
        }
        App.getContext().showMessage(R.string.mine_profile_phone_not_valid)
    }

    fun voiceViewClick(view: View) {
        if (voiceView.isEnabled) {
            val text = edt_phone.text.toString()
            if (Validator.isPhoneNumber(text)) {
                voiceView.isEnabled = false
                voiceView.setTextColor(Color.parseColor("#666666"))
                presenter.getAuthCode(text, 0, 1)
                return
            }
            App.getContext().showMessage(R.string.mine_profile_phone_not_valid)
        }
    }

    fun onEmailRegisterBtnClick(view: View) {
//        startActivity(new Intent(this, EmailRegisterActivity.class).putExtra("type", 1));
//        finish();
    }

    private fun startCountDown() {
        isCountingDown = true
        mTimer = object : CountDownTimer(INTERVAL_1_MIN, INTERVAL_1_SEC) {
            override fun onTick(j: Long) {
                getAuthcodeBtn.text = this@PhoneRegisterActivity.getString(
                    R.string.mine_profile_get_auth_code_time, (j / 1000).toString()
                )
            }

            override fun onFinish() {
                isCountingDown = false
                getAuthcodeBtn.setText(R.string.mine_login_get_message_code)
                getAuthcodeBtn.isEnabled = true
//                authcodeView.text = captcha
            }
        }.start()
    }

    override fun onGetAuthCodeResult(result: Boolean, type: Int) {
        if (type != 1) {
            if (result) {
                inputPhoneNumber = edt_phone.text.toString()
                startCountDown()
            }
        } else if (result) {
            inputPhoneNumber = edt_phone.text.toString()
        } else {
            voiceView.isEnabled = true
            voiceView.setTextColor(Color.parseColor("#ff007ac2"))
        }
    }

    override fun onGetAuthCodeResult(jsonObject: JSONObject) {
        captcha = jsonObject.optString("captcha")
    }

    override fun onDestroy() {
        mTimer?.cancel()
        presenter.destroy()
        super.onDestroy()
    }

    private fun bindView(view: View) {
        getAuthcodeBtn = view.findViewById(R.id.getAuthcodeBtn)
        emailRegisterBtn = view.findViewById(R.id.emailRegisterBtn)
        registerBtn = view.findViewById(R.id.registerBtn)
        voiceView = view.findViewById(R.id.voiceView)
        edt_phone = view.findViewById(R.id.edt_phone)
        edt_pwd = view.findViewById(R.id.edt_pwd)
        edt_pwd_again = view.findViewById(R.id.edt_pwd_again)
        edt_authcode = view.findViewById(R.id.edt_authcode)

        img_del_phone = view.findViewById(R.id.img_del_phone)
        img_del_pwd = view.findViewById(R.id.img_del_pwd)
        img_del_pwd_again = view.findViewById(R.id.img_del_pwd_again)
        img_del_authcode = view.findViewById(R.id.img_del_authcode)

        checkBoxUserAgreement = view.findViewById(R.id.cb_login_user_agreement)
        tvUserAgreement = view.findViewById(R.id.tv_login_user_agreement)
        mRegisterBtn = view.findViewById(R.id.registerBtn)
        mGetAuthcodeBtn = view.findViewById(R.id.getAuthcodeBtn)
        mVoiceView = view.findViewById(R.id.voiceView)
        mEmailRegisterBtn = view.findViewById(R.id.emailRegisterBtn)
        mGetAuthcodeBtn.setOnClickListener(this::getAuthCodeBtnClick)

        img_del_phone.setOnClickListener { it ->
            delete(it, edt_phone)
        }
        img_del_pwd.setOnClickListener { it ->
            delete(it, edt_pwd)
        }
        img_del_pwd_again.setOnClickListener { it ->
            delete(it, edt_pwd_again)
        }
        img_del_authcode.setOnClickListener { it ->
            delete(it, edt_authcode)
        }
    }

    private fun delete(view: View, editText: EditText) {
        editText.setText("")
        view.visibility = View.GONE
    }
}